package com.hele.sts.action.admin;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.hele.sts.dao.*;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hele.sts.pub.StringUtil;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import org.springframework.beans.factory.annotation.Autowired;

public class UserLoginAction
  implements Action
{
  static Logger logger = LoggerFactory.getLogger(UserLoginAction.class);

  @Autowired
  private XtLogDao xtLogDao;

  String action;
  int loginType;
  String loginName;
  String loginPass;
  String certSerial;
  String errorInfo;
  String userName;
  
  @Override
  public String execute()
    throws Exception
  {
	  if (this.action==null) {
	      return "init";
	    }
	  if("login".equalsIgnoreCase(this.action)){
		  if(userName==null) {
              userName="";
          }
		  if(loginPass==null) {
              loginPass="";
          }
		  QUser qUser = QUserDao.login(userName,loginPass);
	  }
    if ("logout".equalsIgnoreCase(this.action)) {
      return logout();
    }
    String sslString = ServletActionContext.getRequest().getHeader("From");
    logger.debug(sslString);
    if ((sslString != null) && (sslString.length() > 0))
    {
      sslString = new String(sslString.getBytes("ISO8859_1"), "GBK");
      String[] ss = sslString.split(":");
      String userName = ss[2];
      logger.debug(userName);
      User user = UserDao.load(userName);
      logger.debug(user + "user");
      if (user == null)
      {
        logger.debug("没有登录！");
        return "error";
      }
      ActionContext ctx = ActionContext.getContext();
      Map session = ctx.getSession();
      session.put("user_name", user.getUserName());
    }
    return "success";
  }
  
  public String logout()
    throws Exception
  {
    ActionContext ctx = ActionContext.getContext();
    Map session = ctx.getSession();
    String userId = (String)session.get("userid");
    if ((userId == null) || ("".equals(userId)))
    {
      setErrorInfo("没有登录或登录超时");
      return "init";
    }
    String yhlx = (String)session.get("yhlx");
    if("2".equals(yhlx)){
    	ret(userId);
    }
    
    
    session.clear();
    session.remove("user_name");

      XtLog log = new XtLog();
      log.setClassname(this.getClass().getName());
      log.setMethod("execute");
      log.setLogtype("业务日志");
      log.setLogname("退出成功");
      log.setCreatetime(new Date(System.currentTimeMillis()));
      log.setSucceed("成功");
      log.setMessage("帐号:"+userName);
      xtLogDao.insert(log);

    return "logout";
  }
  
  private void ret(String userId)
  {
    logger.info("退出时 归还：" + userId);
    QEkUser bean = QEkUserDao.load(userId);
    List qEnterQueueList = QEnterQueueDao.load(userId);
    if (bean != null)
    {
      QUser quser = QUserDao.load(userId);
      if ((qEnterQueueList != null) && 
        (qEnterQueueList.size() > 0))
      {
        Iterator iterator = qEnterQueueList.iterator();
        while (iterator.hasNext())
        {
          QEnterQueue qBean = (QEnterQueue)iterator.next();
          if ((qBean == null) || (quser == null))
          {
            logger.error("qBean is null or quser is null");
          }
          else
          {
            QLog qLog = createrQLog(qBean, quser, bean);
            if (!QLogDao.insert(qLog))
            {
              setErrorInfo("保存日志失败");
              logger.error("保存日志失败");
              return;
            }
          }
        }
        if (!QEnterQueueDao.delete(userId))
        {
          setErrorInfo("删除档案数据失败!");
          logger.error("删除档案数据失败!");
          return;
        }
      }
      quser.setUserName("");
      quser.setCxqx("");
      quser.setDyqx("");
      quser.setStatus("1");
      quser.setGhrq(new Date());
      
      quser.setCxrq(new Date());
      quser.setRealName("");
      quser.setYhsf("");
      quser.setBz("");
      quser.setDyfs("0");
      if (!QUserDao.update(quser))
      {
        setErrorInfo("更新用户失败!");
        return;
      }
    }
  }
  
  QLog createrQLog(QEnterQueue eBean, QUser qUser, QEkUser bean)
  {
    QLog log = new QLog();
    logger.debug(qUser.getCxrq() + "." + StringUtil.createLogId() + "." + 
      eBean.getNbxh() + "." + eBean.getQymc().trim() + "." + 
      eBean.getUserId() + "." + qUser.getYhlx());
    logger.debug(qUser.getUserName() + "." + bean.getUserName() + "." + 
      eBean.getZch());
    
    log.setCxrq(new Date());
    log.setLogId(StringUtil.createLogId());
    log.setNbxh(eBean.getNbxh().trim());
    log.setQymc(eBean.getQymc().trim());
    log.setUserId(eBean.getUserId().trim());
    log.setUserName(qUser.getUserName().trim());
    log.setUserNameEk(bean.getUserName().trim());
    log.setYhlx(qUser.getYhlx().trim());
    log.setZch(eBean.getZch().trim());
    
    log.setRealName(qUser.getRealName());
    log.setYhsf(qUser.getYhsf());
    log.setBz(qUser.getBz());
    log.setDyfs(qUser.getDyfs());
    //xuning add 20150101
    log.setCxmd(qUser.getCxmd());
    return log;
  }
  
  public String getErrorInfo()
  {
    return this.errorInfo;
  }
  
  public void setErrorInfo(String errorInfo)
  {
    this.errorInfo = errorInfo;
  }
  
  public String getLoginName()
  {
    return this.loginName;
  }
  
  public void setLoginName(String loginName)
  {
    this.loginName = loginName;
  }
  
  public String getLoginPass()
  {
    return this.loginPass;
  }
  
  public void setLoginPass(String loginPass)
  {
    this.loginPass = loginPass;
  }
  
  public int getLoginType()
  {
    return this.loginType;
  }
  
  public void setLoginType(int loginType)
  {
    this.loginType = loginType;
  }
  
  public String getCertSerial()
  {
    return this.certSerial;
  }
  
  public void setCertSerial(String certSerial)
  {
    this.certSerial = certSerial;
  }
  
  public String getAction()
  {
    return this.action;
  }
  
  public void setAction(String action)
  {
    this.action = action;
  }
}
